import { defineStore } from 'pinia';
import { AuthState } from '@/stores/interface';
import { getMenuList } from '@/api/modules/login';

import { getKeepAliveRouterName, getShowMenuList, getAllBreadcrumbList, getMenuLists } from '@/utils/util';
import piniaPersistConfig from '@/config/piniaPersist';

// AuthStore
export const AuthStore = defineStore('AuthState', {
	state: (): AuthState => ({
		// 按钮权限列表
		authButtonList: [],
		// menuList 作为动态路由，不会做持久化存储
		authMenuList: [],
		// 子系统菜单
		sysMenuList: [],
		// 选择的子系统菜单id
		selectedSysId: 21,
		// 需要缓存的菜单 name，用作页面 keepAlive
		keepAliveRouter: []
	}),
	getters: {
		// 按钮权限列表
		authButtonListGet: state => state.authButtonList,
		// 后端返回的菜单列表
		authMenuListGet: state => state.authMenuList,
		// 后端返回的菜单列表 ==> 左侧菜单栏渲染，需要去除 isHide == true
		showMenuListGet: state => getShowMenuList(state.authMenuList),
		// 面包屑导航列表
		breadcrumbListGet: state => getAllBreadcrumbList(state.authMenuList),
		// 需要缓存的菜单 name，用作页面 keepAlive
		keepAliveRouterGet: state => getKeepAliveRouterName(state.authMenuList),
		// 过滤子系统菜单
		sysMenuListGet: state => state.sysMenuList
	},
	actions: {
		// 设置需要缓存的菜单 name
		setKeepAliveRouter(name: string) {
			this.keepAliveRouter.push(name);
		},
		// 删除需要缓存的菜单 name
		deleteKeepAliveRouter(name: string) {
			this.keepAliveRouter = this.keepAliveRouter.filter(item => item !== name);
			console.log(this.keepAliveRouter);
		},
		// getAuthButtonList
		async getAuthButtonList(data: string[]) {
			this.authButtonList = data;
		},
		// getAuthMenuList
		async getAuthMenuList() {
			const { menuList, permissions } = await getMenuList();
			this.getAuthButtonList(permissions);
			const homePath: Menu.MenuOptions[] = [
				{
					path: '/home/index',
					name: '首页',
					icon: 'HomeFilled',
					component: '/home/index',
					menuId: 99999,
					perms: '/home/index',
					meta: {
						title: '首页',
						isLink: '',
						isHide: true,
						isFull: false,
						isAffix: true,
						isKeepAlive: true
					}
				}
			];
			const datas: Menu.MenuOptions[] = homePath.concat(menuList as any);
			this.authMenuList = getMenuLists(datas);
			this.keepAliveRouter = this.keepAliveRouterGet;
		},

		// selectedSysId
		async setSelectedSysId(id: number) {
			this.selectedSysId = id;
		}
	},
	persist: piniaPersistConfig('AuthState', ['authButtonList'])
});
